define(["../common"], function() {
	var formTypes = {ADD: "add", EDIT: "edit"},
	formType = formTypes.ADD,
	
	codeGoodsPath = g_firmDomain + "/goods/oneByCode/json",
	saveDoPath = g_firmDomain + "/goods/addOrEditDo/json",
	makeCodePath = g_firmDomain + "/company/barCode/json",
	
	hideData = $.parseJSON($("#hideData").html());

	var sel = {
		goodsForm: "#goodsForm",
		goodsId: "#goodsId",
		barCode4Add: "#barCode4Add",
		barCode4Edit: "#barCode4Edit",
		barCode: "#barCode",
		editBt: "#editBt",
		genCodeBt: "#genCodeBt",
		genCodeOtherBt: "#genCodeOtherBt",
		catId: "#catId",
		selectCats: "#selectCats",
		categoryPath: "#categoryPath",
		selectClassify: "#selectClassify",
		classifyId: "#classifyId",
		unit: "#unit",
		tunit: "[id^='unitF']",
		sellUnit: "#sellUnit",
		tsellUnit: function(id) {return id !== undefined?("#sellUnitF" + id):"[id^='sellUnitF']";},
		convertContent: "#convertContent",
		unitConvert: "#unitConvert",
		pic: "#pic",
		imgPrev: "#imgPrev",
		picFileBt: "#picFileBt",
		submitBt: "[id^='submitBt_']",
		syncItem: "#syncFieldsItem",
		syncContainer: "#syncFieldsContainer",
		syncFields: "[name='syncField']",
		sync: "#sync"
	};

	// 事件:左侧类目点击事件
	$("#fl a[id^='classifyId_']").click(function() {
		$(this).showMsg('正在查询...', 'load');
		location.href = g_firmDomain + "/goods/list?goodsClassify.classifyId=" + ($(this).attr("id").split("_"))[1];
	});

	// 表单验证设置
	var formConfig = {
		rules: {
			validFormat: validFormat,
			validExsits: validExsits
		},
		fields: {
			barCode: {
				rule: 'required;digits;validFormat;validExsits',
				msg: {
					validExsits: "商品已经存在，<a id='editBt' style='color:#06F'>点击编辑</a>"
				}
			},
			name: 'required;length[~80]',
			title: 'required;length[~80]',
			subTitle: 'length[~80]',
			keywords: 'required;length[~50]',
			'category.catId': {
				rule: 'required',
				msg: {required: "请选择类目"}
			},
			'goodsClassify.classifyId': {
				rule: 'required',
				msg: {required: "请选择类目"}
			},
			unit: {
				rule: 'required;length[~10]',
				target: "#unitMsg"
			},
			price: {
				rule: 'required;money;range[~999999]',
				target: "#priceMsg"
			},
			sellUnit: {
				rule: 'match[neq, unit];length[~10]',
				msg: {match: "不能与计费单位相同"},
				target: "#sellUnitMsg"
			},
			unitConvert: {
				rule: 'required;amount;range[0.01~];range[~99]',
				msg: {range: "只能是大于0的值"},
				target: "#unitConvertMsg"
			},
			stockEnd: {
				rule: 'required;amount;range[~99]',
				target: "#stockEndMsg"
			},
			sellMin: {
				rule: 'required;amount;range[~99]',
				target: "#sellMinMsg"
			},
			sellDef: {
				rule: 'required;amount;match[gte, sellMin];range[~99]',
				msg: {match: "不能于小最小出售量"},
				target: "#sellDefMsg"
			},
			sellExt: {
				rule: 'required;amount;range[~99]',
				tip: "用户购买量是此值的倍数"
			},
			descrDef: 'required'
		},
		valid: submitGoodsForm
	};
	
	// 加载商品信息(编辑)
	if ($(sel.barCode).val()) {
		formType = formTypes.EDIT;
		initGoodsForm($(sel.barCode).val());
	} else {
		initCategory();
		initClassify();
	}

	if (formType === formTypes.EDIT) {
		formConfig.fields.barCode = null;// 忽略编码验证
		$(sel.barCode4Edit).show();
	} else {
		$(sel.barCode4Add).show();
	}
	loadjs(["validator"], function() {
		$(sel.goodsForm).validator(formConfig);
	});

	// 事件:编辑
	$(document).on('click', sel.editBt, function() {
		location.href = "?barCode=" + $(sel.barCode).val();
	});

	// 解决焦点在编码表单时，“点击编辑”要点两次才起效的问题
	$(document).on('mouseover', sel.editBt, function() {
		if ($(sel.barCode).is(":focus")) {// 没有此句将无法触发以下的mouseout
			$(sel.barCode).blur();
		}
	});
	$(document).on('mouseout', sel.editBt, function() {
		$(sel.barCode).focus();
	});

	// 事件:生成店内码(打秤类)
	$(sel.genCodeBt).click(function() {
		genCode($(this));
	});
	
	// 事件:生成店内码(其它)
	$(sel.genCodeOtherBt).click(function() {
		genCode($(this), 'other');
	});

	// 事件：修改计费单位
	$(sel.unit).change(function() {
		$(sel.tunit + "," + sel.tsellUnit("Text")).html($(this).val());
	});

	// 事件：修改购买单位
	$(sel.sellUnit).change(function() {
		var sellUnit = $(this).val();
		if(sellUnit) {
			$(sel.convertContent).show();
			$(sel.tsellUnit("Convert") + "," + sel.tsellUnit("Text")).html(sellUnit);
		} else {
			$(sel.convertContent).hide();
			$(sel.tsellUnit("Text")).html($(sel.unit).val());
		}
	});

	// 事件:保存
	$(sel.submitBt).click(function() {
		var ignore = null;
		if (!$(sel.sellUnit).val()) {
			ignore = sel.unitConvert;
		}
		$(sel.goodsForm).data('validator').options.ignore = ignore;
		$(sel.goodsForm).trigger('validate');
	});

	function genCode($target, type) {
		if (!$target.showMsg("正在生成店内码...", 'load', true)) return;
		$.post(makeCodePath + "?r=" + Math.random(), function(data) {
			if (data.status !== 0) {
				$target.showMsg(data.message, 'error');
				return;
			}
			if (type == 'other') {
				$(sel.barCode).val((1e6 + parseInt(data.result)).toFixed(0));
			} else {
				$(sel.barCode).val(data.result);				
			}
			$target.showMsg();
		});
	}

	function validFormat(el, param, field) {
		if (!checkBarCode($(el).val())) {
			return "格式不正确";
		}
	}

	function validExsits(el, param, field) {
		return $.post(g_firmDomain + "/goods/check4AddDo/json", {barCode: $(el).val()}, function(data) {
			if (data.status !== 0) {
				$(el).showMsg(data.message, 'error');
				return;
			}
			// 缓存已经存在的商品信息
			$(document).data("goods", data.result);
		});
	}

	function checkBarCode(barCode) {
		var c = barCode;
		// 店内码
		if (c.length === 5 || (c.length >5 && c.length < 11)) {
			return true;
		}
		// 国际零售商品条码
		return c.length === 13 && parseInt(c[c.length -1]) === getCheckCode(c);
	}

	// 计算出校验码
	function getCheckCode(barCode) {
		var c = barCode;
		var check = 0;
		var odd = 0;
		var even = 0;
		for (var i = c.length - 2; i >= 0; i -= 2) {
			odd += parseInt(c[i]);
		}
		for (var i = c.length - 3; i >= 0; i -= 2) {
			even += parseInt(c[i]);
		}
		check = odd * 3 + even;
		return parseInt(check / 10) * 10 + (check % 10 === 0 ? 0 : 10) - check;
	}


	// 提交商品信息表单
	function submitGoodsForm(form) {
		if (!$(form).showMsg("正在保存...", 'load', true)) return;
		
		// 各级类名拼接
		var $selectedSelect = $("#selectCats select option:selected[value!='']");
		var catPath = $selectedSelect.map(function() {
			return $(this).val()?$(this).text():"";
		}).get().join(" > ");
		$(sel.categoryPath).val(catPath);
		
		$.post(saveDoPath, $(form).serialize(), function(data){
				if (data.status !== 0) {
					$(form).showMsg(data.message, 'error');
					return;
				} 
				
				$(form).showMsg("保存成功", 'pass');
				if (data.result) {
					$(sel.goodsId).val(data.result);
				}
		});
	}

	// 初始表单数据
	function initGoodsForm(barCode) {
		$.post(codeGoodsPath, {barCode: barCode}, function(data) {
			var goods = data.result;
			if (!goods) {
				return;
			}
			//  给表单赋值
			setValues(goods, null);
			// 其它
			$(sel.tunit + "," + sel.tsellUnit("Text")).html(goods.unit);
			if (goods.sellUnit) {
				$(sel.tsellUnit("Convert") + "," + sel.tsellUnit("Text")).html(goods.sellUnit);
				$(sel.convertContent).show();
			}
			$(sel.imgPrev).attr('data', goods.pic);
			$(window).scroll();
			initCategory();
			initClassify();
			showSyncFields();
		});
	}

	// 根据商品信息给编辑表单赋值
	function setValues(result, nodeName) {
		var fullKey;
		for (var key in result) {
			fullKey = nodeName? (nodeName + '.' + key) : key;
			if ($.isPlainObject(result[key])) {
				setValues(result[key], fullKey);
			} else {
				$("[name='" + fullKey + "']").val(result[key]);
			}
		}
	}

	// 初始化系统类目选项
	function initCategory() {
		$(sel.selectCats).empty();
		loadjs(["category"], function() {
			$(sel.selectCats).categoryComboBox({
				value: $(sel.catId).val(),
				nullName: "-选择-",
				onSelect: function(deep, category) {
					$(sel.catId).val(category?category.catId:"");
					$(sel.catId).trigger('validate');
				}
			});
		});
	}

	// 初始化企业类目选项
	function initClassify() {
		$(sel.selectClassify).empty();
		require(["goodsClassify"], function() {
			$(sel.selectClassify).goodsClassifyComboBox({
				value: $(sel.classifyId).val(),
				companyId: hideData.companyId,
				nullName: "-选择-",
				onSelect: function(deep, classify) {
					$(sel.classifyId).val(classify?classify.classifyId:"");
					$(sel.classifyId).trigger('validate');
				}
			});
		});
	}

	// 加载店铺商品同步选项
	function showSyncFields() {
		$(sel.syncItem).show();
		var key = "syncFields";
		var data = Common.getLocalStorage(key);
		if (data) {
			showSyncFields_(data);
		} else {
			$.get(g_firmDomain + "/goods/syncFields/json", function(data) {
				Common.setLocalStorage(key, data);
				showSyncFields_(data);
			}, 'html');
		}
		
		function showSyncFields_(data) {
			var fields = $.parseJSON(data).result;
			var field;
			for (var i in fields) {
				field = fields[i];
				$(sel.syncContainer).append("<input type='checkbox' name='syncField' value='" + field.ordinal + "'>" + field.text);
			}
			$(sel.syncFields).click(function() {
				var ordinal = -1,syncType = 0;
				$(sel.syncFields + ":checked").each(function() {
					ordinal = parseInt($(this).val());
					syncType |= (1 << ordinal);
				});
				$(sel.sync).val(syncType);
			});
			// 默认选中"企业类目"
			$(sel.syncFields + "[value='4']").trigger('click');
		}
	}	
	
	// 商品图片相关
	require(["ckfinder"], function() {
		// 图片库
		var finder = new CKFinder();
		finder.connectorInfo = "attaType=COMPANY";
		finder.resourceType = 'Images';
		finder.selectActionData = "container";
		finder.selectActionFunction = function(fileUrl, data) {
			$(sel.pic).val(fileUrl);
			$(sel.imgPrev).attr('data', fileUrl);
			$(window).scroll();
			
		};
		
		// 事件：弹出图片库
		$(sel.picFileBt).click(function() {
			finder.popup();
		});
	});
});
